package leetcode.code0546;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

/**
 * 执行用时：122 ms, 在所有 Java 提交中击败了41.32%的用户
 *
 * 内存消耗：48.5 MB, 在所有 Java 提交中击败了18.18%的用户
 *
 * 通过测试用例：63 / 63
 */
public class Solution implements IDebug {

	public int removeBoxes(int[] boxes) {
		int N = boxes.length;
		Integer[][][] dp = new Integer[N][N][N];
		return this.f(boxes, 0, N - 1, 0, dp);
	}

	private int f(int[] boxes, int L, int R, int K, Integer[][][] dp) {
		if (L > R) {
			return 0;
		}
		if (dp[L][R][K] != null) {
			return dp[L][R][K];
		}
		int ans = this.f(boxes, L + 1, R, 0, dp) + (K + 1) * (K + 1);
		for (int i = L + 1; i <= R; i++) {
			if (boxes[i] == boxes[L]) {
				ans = Math.max(ans, this.f(boxes, L + 1, i - 1, 0, dp) + this.f(boxes, i, R, K + 1, dp));
			}
		}
		dp[L][R][K] = ans;
		return ans;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(23, this.removeBoxes(HelpDebug.str2array3("[1,3,2,2,2,3,4,3,1]")));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(9, this.removeBoxes(HelpDebug.str2array3("[1,1,1]")));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(1, this.removeBoxes(HelpDebug.str2array3("[1]")));

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
